﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using BLL;
using DAL;
using DataProj.Areas.BackSys.ServiceTools;
using DataProj.Controllers;
using MQTools;
using Newtonsoft.Json;
using RabbitMQ.Client;

namespace DataProj.Areas.BackSys.Controllers
{
    public class HomeController : Controller
    {
        private static bool isExpire = false; //Session是否超时
        private static DeliverymanImpl deliverymanImpl;
        private static UserinfoImpl userinfoImpl;
        //private static BagInfoImpl bagInfoImpl;
        private static ManagerImpl managerImpl;
        //private static ComplaintImpl complaintImpl;

        public HomeController()
        {
            
            if (userinfoImpl == null) userinfoImpl = new UserinfoImpl();
            if (managerImpl == null) managerImpl = new ManagerImpl();
            if (deliverymanImpl == null) deliverymanImpl = new DeliverymanImpl();
  
        }


        [HttpGet, ActionName("Login")]
        // GET: BackSys/Login
        public ActionResult IdentityValidate()
        {
            //return new RedirectResult("Main");
            if (!string.IsNullOrEmpty(MySession.GetSession("loginType")) )
            {
                return RedirectToAction("Index", "Welcome");
            }
            return View();
        }






        //[HttpPost]
        //public ActionResult Index(string name, string password, string returnUrl)
        //{
        //    /*
        //      添加验证用户名密码代码
        //    */
        //    MySession.WriteSession("userName", name);
        //    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
        //    {
        //        return Redirect(returnUrl);
        //    }
        //    else
        //    {
        //        return RedirectToAction("Index", "Home");
        //    }
        //}

        // POST: /Account/LogOut

        //public ActionResult Save()
        //{
        //    var sr = new StreamReader(Request.InputStream);
        //    var stream = sr.ReadToEnd();
        //    JavaScriptSerializer js = new JavaScriptSerializer();
        //    var list = js.Deserialize<List<SelectList>>(stream);
        //    if (list.Any())
        //    {
        //        foreach (var item in list)
        //        {

        //        }
        //    }
        //    return PartialView()();
        //}
        //public partial class SelectList
        //{
        //    public int id { get; set; }

        //    public string name { get; set; }

        //    public string text { get; set; }
        //}

        [HttpGet]
        public ActionResult Registration()
        {
            //UserInfo user = new UserInfo();
            //user.UserName = Request["UserName"];
            //user.UserPass = Request["UserPass"];
            //user.TrueName = Request["TrueName"];
            //user.Phone = Request["Phone"];
            //user.Email = Request["Email"];
            //user.IDCard = Request["IDCard"];
            //user.ContactAddress = Request["Address"];
            //user.AddTime = DateTime.Now;
            //if (new UserinfoImpl().Add(user)) return Json(1, JsonRequestBehavior.AllowGet);

            //return Json(0, JsonRequestBehavior.AllowGet);
            return PartialView();
        }

        [HttpPost, ActionName("Registration")]
        public ActionResult ProcessRegistration()
        {
            UserInfo user = new UserInfo();
            var impl = new UserinfoImpl();
            user.ID=impl.GetList().Last().ID + 1;
            user.UserName = Request["UserName"];
            user.UserPass = Request["UserPass"];
            user.TrueName = Request["TrueName"];
            user.Phone = Request["Phone"];
            user.Email = Request["Email"];
            user.IDCard = Request["IDCard"];
            user.ContactAddress = Request["Address"];
            user.AddTime = DateTime.Now;
            if (impl.Add(user)) {
                using (MQSender MqSender = new MQSender(Resources.HostName,Resources.VirtualHost,Resources.UserName,Resources.Password,Resources.Exchange,ExchangeType.Topic) )
                {
                    MqSender.SendMessage(new QueueMessage() { Action = QueueMessage.ActionType.USER_REGISTER, User = user }, Resources.CompanyUserRoute);
                    return Json(1);
                }
               
            }

            return Json(0);
        }



        [HttpPost, ActionName("Login")]
        public ActionResult ProcessRequest()
        {
           
            var name = HttpContext.Request["userName"].Trim();
            var pass = HttpContext.Request["userPass"].Trim();

            var userInfo = userinfoImpl.Login(name, pass);
            if (userInfo != null)
            {
                MySession.WriteSession("loginType", "用户");
                MySession.WriteSession("id", userInfo.ID);
                MySession.WriteSession("detail", userInfo);
                MySession.WriteSession("userName", userInfo.UserName);
                MySession.WriteSession("userID", userInfo.ID);
                
                return Json(1);
            }
            var managerInfo = managerImpl.Login(name, pass);
            if (managerInfo != null)
            {

                MySession.WriteSession("loginType", "管理员");
                MySession.WriteSession("id", managerInfo.ID);
                MySession.WriteSession("detail", managerInfo);
                MySession.WriteSession("userName", managerInfo.UserName);
                MySession.WriteSession("userID", managerInfo.ID);
                return Json(1);
            }
            var deliverymanInfo = deliverymanImpl.Login(name, pass);
            if (deliverymanInfo != null)
            {
                MySession.WriteSession("loginType", "快递员");
                MySession.WriteSession("id", deliverymanInfo.ID);
                MySession.WriteSession("detail", deliverymanInfo);
                MySession.WriteSession("userName", deliverymanInfo.UserName);
                MySession.WriteSession("userID", deliverymanInfo.ID);
                return Json(1);
            }
        
            return Json(0);

        }



        protected void Session_End(object sender, EventArgs e)
        {
            isExpire = true;

            //Session.Abandon();
        }
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            bool IsAjax = Request.IsAjaxRequest();
            if (isExpire && (IsAjax == false))
            {
                isExpire = false;
                Response.Write("<script languge='javascript'>alert('用户信息已过期，请重新登录');window.parent.location.href='/Home/LogOut';</script>");
                Response.End();
                //Response.Redirect("~/Home/LogOut");
            }
        }

    }
}